package com.rt.easyjava.base.modules.timerjob.service.job.jobStrategy;

import com.rt.easyjava.common.config.SpringContextBaseHolder;
import com.rt.tmpt.service.utils.SpringContextHolder;
import com.rt.easyjava.base.modules.timerjob.bean.TmptTimerLogBiz;
import com.rt.easyjava.base.modules.timerjob.dto.TmptTimerBizDto;
import com.rt.easyjava.base.modules.timerjob.service.intf.TmptTimerLogBizService;
import com.rt.easyjava.common.base.Result;
import com.rt.easyjava.common.utils.others.DateTool;

public abstract class JobStrategy {
    protected TmptTimerBizDto tmptTimerBizDto;
    protected Result typeResult;

    public Result execute(){
        // 开始日志
        TmptTimerLogBizService tmptTimerLogBizService = SpringContextBaseHolder.getBean("tmptTimerLogService");
        TmptTimerLogBiz tmptTimerLogBiz = createLogStart(tmptTimerLogBizService, tmptTimerBizDto.getId());
        String resultString = "";
        try {
            // 执行job()
            resultString = job();
            // 记结束日志
            createLogEnd(tmptTimerLogBizService, tmptTimerLogBiz, resultString);
            return Result.builder().success(resultString);
        } catch (Exception e) {
            // 记结束异常日志
            createLogEnd(tmptTimerLogBizService, tmptTimerLogBiz, e.getMessage());
            resultString = e.getLocalizedMessage();
            return Result.builder().fault(resultString);
        }
    }

    protected abstract String job() throws Exception;

    private TmptTimerLogBiz createLogStart(TmptTimerLogBizService tmptTimerLogBizService, Long tmptTimerId) {
        TmptTimerLogBiz tmptTimerLogBiz = new TmptTimerLogBiz();
        tmptTimerLogBiz.setTmptTimerId(tmptTimerId);
        tmptTimerLogBiz.setStartTime(DateTool.getCurrentDatetime("yyyy-MM-dd HH:mm:ss.SSS"));
        tmptTimerLogBiz.setCreatedate(DateTool.getCurrentDatetime("yyyy-MM-dd HH:mm:ss.SSS"));
        tmptTimerLogBiz.setResult("start, waiting result ...");
        tmptTimerLogBizService.save(tmptTimerLogBiz);
        return tmptTimerLogBiz;
    }

    private void createLogEnd(TmptTimerLogBizService tmptTimerLogBizService, TmptTimerLogBiz tmptTimerLogBiz, String result) {
        tmptTimerLogBiz.setEndTime(DateTool.getCurrentDatetime("yyyy-MM-dd HH:mm:ss.SSS"));
        tmptTimerLogBiz.setModifydate(DateTool.getCurrentDatetime("yyyy-MM-dd HH:mm:ss.SSS"));
        tmptTimerLogBiz.setResult(result);
        tmptTimerLogBizService.saveOrUpdate(tmptTimerLogBiz);
    }
}
